from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
import uvicorn
from models import DBItem
from schemas import ItemCreate, ItemResponse
from database import get_db, engine, Base
from sqlalchemy.future import select

app = FastAPI()

# 创建数据库表（生产环境应使用迁移工具如Alembic）
@app.on_event("startup")
async def startup():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

# 创建项目
@app.post("/items/", response_model=ItemResponse)
async def create_item(item: ItemCreate, db: AsyncSession = Depends(get_db)):
    db_item = DBItem(**item.dict())
    db.add(db_item)
    await db.commit()
    await db.refresh(db_item)
    return db_item

# 获取所有项目
@app.get("/items/", response_model=list[ItemResponse])
async def read_items(db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(DBItem))
    return result.scalars().all()

# 获取单个项目
@app.get("/items/{item_id}", response_model=ItemResponse)
async def read_item(item_id: int, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(DBItem).where(DBItem.id == item_id))
    item = result.scalar()
    if not item:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

# 更新项目
@app.put("/items/{item_id}", response_model=ItemResponse)
async def update_item(
    item_id: int,
    item: ItemCreate,
    db: AsyncSession = Depends(get_db)
):
    result = await db.execute(select(DBItem).where(DBItem.id == item_id))
    db_item = result.scalar()
    if not db_item:
        raise HTTPException(status_code=404, detail="Item not found")
    
    for key, value in item.dict().items():
        setattr(db_item, key, value)
    
    await db.commit()
    await db.refresh(db_item)
    return db_item

# 删除项目
@app.delete("/items/{item_id}")
async def delete_item(item_id: int, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(DBItem).where(DBItem.id == item_id))
    db_item = result.scalar()
    if not db_item:
        raise HTTPException(status_code=404, detail="Item not found")
    
    await db.delete(db_item)
    await db.commit()
    return {"message": "Item deleted"}
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
  